import axios from 'axios'
import { getToken } from './getUserInfo.js'

let map = new Map()
map.set('get', get)
map.set('post', post)
map.set('put', put)
map.set('delete', del)

//在axios请求的过程中，会自动拼接这一串路径
axios.defaults.baseURL = `http://127.0.0.1:8888/api/private/v1/`

//axios的请求拦截
axios.interceptors.request.use(function(config) {
  //设置请求头中的Authorization为token值
  config.headers['Authorization'] = getToken()
  return config
})

/**
 * 封装请求函数
 * @date 2021-01-09
 * @param {Object} option {type:'post',url:'login',data:{usernam:'admin',password:'123456'}}
 * @returns {Promise}
 */
async function request(option) {
  //参数的判断
  if (!map.get(option.type)) {
    return null
  }
  let method = map.get(option.type)
  let res = await method(option)
  return res
}

async function get(option) {
  return await axios.get(option.url, { params: option.data })
}
async function post(option) {
  return await axios.post(option.url, option.data)
}
async function put(option) {
  return await axios.put(option.url, option.data)
}
async function del(option) {
  return await axios.delete(option.url, { params: option.data })
}

export default request
